<template>
  <div>
    <!-- 已登录显示数据 -->
    <div v-if="loginStatus === 'showData'" :class="!isMobilePage ? 'fileListPcClass' : 'fileListMobileClass'">
      <div class="area-header" style="text-align: center;">
        <h4>{{ $t(form.shareTitle) }}</h4>
      </div>
      <el-table v-if="!isMobilePage" v-loading="loading" :data="form.fileList" border style="overflow: auto; height: 400px;">
        <el-table-column :label="$t('序号')" align="center" width="50">
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件名称')" align="left" prop="fileName">
          <template slot-scope="scope">
            <el-link :underline="false" type="primary" @click="onlinePreviewOnlineEdit('view', scope.row.fileId)">
              <i :class="formatSuffix(scope.row.fileName)" style="margin-right: 5px;margin-bottom: 5px;" />{{ $t(scope.row.fileName) }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column :label="$t('文件大小')" align="center" prop="sizes" width="130">
          <template slot-scope="scope">
            <span>{{ calculateFileSize(scope.row.sizes) }} {{ calculateFileSize(scope.row.size) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('上传时间')" align="center" prop="updateTime" width="180" />
        <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-view"
              @click="onlinePreviewOnlineEdit('view', scope.row.fileId)"
            >{{ $t('查看') }}</el-button>
            <el-button
              v-if="form.edit === 'Y'"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="onlinePreviewOnlineEdit('review', scope.row.fileId)"
            >{{ $t('编辑') }}</el-button>
            <el-button
              v-if="form.download === 'Y'"
              size="small"
              type="text"
              icon="el-icon-download"
              @click="downloadFile(scope.row.fileId)"
            >{{ $t('下载') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="isMobilePage">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item v-for="(item,index) in form.fileList" :key="item.id" :title="item.fileName" :name="index + ''" class="collapseCustom">
            <el-descriptions title="" :column="1">
              <el-descriptions-item label="名称">{{ item.fileName }}</el-descriptions-item>
              <el-descriptions-item label="大小">{{ calculateFileSize(item.sizes) }} {{ calculateFileSize(item.size) }}</el-descriptions-item>
              <el-descriptions-item label="时间">{{ item.updateTime }}</el-descriptions-item>
              <el-descriptions-item label="操作">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-view"
                  @click="onlinePreviewOnlineEdit('view', item.fileId)"
                >{{ $t('查看') }}</el-button>
                <el-button
                  v-if="form.edit === 'Y'"
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="onlinePreviewOnlineEdit('review', item.fileId)"
                >{{ $t('编辑') }}</el-button>
                <el-button
                  v-if="form.download === 'Y'"
                  size="small"
                  type="text"
                  icon="el-icon-delete"
                  @click="downloadFile(item.fileId)"
                >{{ $t('下载') }}</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <!-- 分享失效 -->
    <div v-if="loginStatus === 'Unshared' || loginStatus === 'ShareExpired'" :style="{ 'height': windowHeight, 'width': windowWidth }">
      <div class="login">
        <div style="width: 60%; height: 50%; border: solid 1px #afcdd4; margin: auto; margin-top: 15vh; background-color: white;">
          <div style="color: #424e67;text-align: center; padding: 140px 0 0; font-weight: 200; font-size: 14px; width: 100%;">
            <div style="width: 75px;height: 75px;border: 0px solid;margin: auto; border-radius: 50px; background: #bbdaff;">
              <span style="font-size: 60px; color: #459aff; font-family: fangsong;">!</span>
            </div>
            <div style="margin-top: 20px;">
              <span v-if="loginStatus === 'Unshared'">{{ $t('非常抱歉，分享的文件已经被取消，请联系相关人员。') }}</span>
              <span v-if="loginStatus === 'ShareExpired'">{{ $t('非常抱歉，分享的文件已经失效了，请联系相关人员。') }}</span>
            </div>
            <div class="el-login-footer" style="width: 60%;">
              <span>Copyright © 2016-2025 {{ $t('北京安信立融科技股份有限公司') }} - Powered By {{ $t('J博士') }}V4.0</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 未登录打开登陆页面 -->
    <div v-if="loginStatus === 'login'" :style="{ 'height': windowHeight }">
      <div class="login">
        <div class="loginDiv">
          <el-form ref="login" v-loading="loginLoading" :model="login" :rules="rules" class="login-form login-form-reset">
            <div class="logo" />
            <h3 class="title">{{ $t('J博士投资管理系统') }}</h3>
            <el-divider><i class="el-icon-key" /></el-divider>
            <el-form-item prop="userName">
              <el-input v-model="login.userName" size="mini" clearable :placeholder="$t('访问名')" />
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="login.phone" size="mini" clearable :placeholder="$t('手机号')" />
            </el-form-item>
            <el-form-item prop="tenantCode">
              <el-input v-model="login.tenantCode" size="mini" clearable :placeholder="$t('机构编码')" />
            </el-form-item>
            <el-form-item prop="code">
              <el-input v-model="login.code" size="mini" clearable :placeholder="$t('验证码')">
                <template slot="append">
                  <div v-if="!repeatClick" style="padding: 0 10px;">
                    <el-button v-if="btnShow" type="text" :disabled="disabled" @click="getCode">{{ $t('获取验证码') }}</el-button>
                    <span v-else>{{ num }}</span>
                  </div>
                  <div v-else style="padding: 0 10px;">
                    <el-button type="text" disabled icon="el-icon-loading">{{ $t('正在获取') }}</el-button>
                  </div>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item style="width:100%;">
              <el-button
                size="small"
                type="primary"
                style="width:100%;margin-top: 5px;"
                @click.native.prevent="viewLogin"
              ><span>{{ $t('确定') }}</span></el-button>
            </el-form-item>
          </el-form>
        </div>

        <!--  底部  -->
        <div class="el-login-footer">
          <span>Copyright © 2016-2025 {{ $t('北京安信立融科技股份有限公司') }} - Powered By {{ $t('J博士') }}V4.0</span>
        </div>
      </div>
    </div>
    <!-- 附件预览 -->
    <OnlinePreview ref="OnlinePreview" />
  </div>
</template>

<script>
import { viewSharedFiles, SMSVerificationCode } from '@/api/file/share/sysShareFiles.js'
import { downLoadFileOpen } from '@/utils/zipdownload'
import Cookies from 'js-cookie'
export default {
  data() {
    const checkPhone = (rule, value, callback) => {
      // this.disabled = true
      if (value === undefined || value === '' || value === null) {
        callback(new Error(this.$t('必填字段')))
      } else if (value.length !== 11) {
        callback(new Error(this.$t('请输入11位手机号码')))
      } else {
        var reg = /^1[3456789]\d{9}$/
        if (!reg.test(value)) {
          callback(new Error(this.$t('请输入有效的手机号码')))
        } else {
          // this.disabled = false
          callback()
        }
      }
    }
    return {
      windowHeight: document.body.clientHeight + 'px',
      windowWidth: document.body.clientWidth + 'px',
      loading: false,
      loginStatus: 'login',
      form: {},
      login: {
        userName: '',
        phone: '',
        code: '',
        tenantCode: ''
      },
      loginLoading: false,
      btnShow: true,
      num: 60,
      repeatClick: false,
      rules: {
        userName: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        phone: [{ required: true, validator: checkPhone, trigger: ['blur', 'change'] }],
        code: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        tenantCode: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      isMobilePage: false,
      activeName: undefined
    }
  },
  computed: {
    disabled() {
      if (this.login.userName && this.login.phone) {
        if (this.login.phone !== '' && this.login.phone !== null) {
          if (this.login.phone.length === 11) {
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      } else {
        return true
      }
    }
  },
  created() {
    this.init('check')
    // 自动添加机构编号
    var query = encodeURI(window.location.search.substring(1))
    var vars = query.split('&')
    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=')
      if (pair[0] === 'tenantCode') {
        const result = pair[1]
        if (result !== null && result !== undefined && result !== '') {
          console.log(result)
          this.login.tenantCode = result
        }
      }
    }
    // 判断是否是移动端
    if (window.innerWidth < 500) {
      this.isMobilePage = true
    } else {
      this.isMobilePage = false
    }
  },
  methods: {
    // 初始化数据
    init(type) {
      this.loading = true
      const id = this.$route.query.id
      this.loginStatus = 'login'
      if (id) {
        viewSharedFiles(id, type, this.login.userName, this.login.phone, this.login.code, this.login.tenantCode, this.getToken()).then(response => {
          console.log(response.data)
          if (response.data.login) {
            console.log('登陆用户')
            this.loginStatus = 'showData'
            this.form = response.data.data
            if (this.form === null && response.data.count === 0) {
              this.loginStatus = 'Unshared'
            } else if (this.form === null && response.data.count === 1) {
              this.loginStatus = 'ShareExpired'
            }
          } else {
            console.log('外部用户')
            if (response.data.data !== undefined && response.data.data !== null) {
              this.setToken(response.data.data)
              this.init('check')
            }
            this.loginStatus = 'login'
          }
          this.loading = false
        })
      } else {
        this.loading = false
      }
    },
    // 计算文件大小  换算单位
    calculateFileSize(size) {
      size = parseInt(size)
      if (size > 0 && size < 1048576) {
        return (size / 1024).toFixed(2) + ' KB'
      } else if (size > 1048576) {
        return (size / 1024 / 1024).toFixed(2) + ' MB'
      } else {
        return ''
      }
    },
    formatSuffix(fileName) {
      var suffix = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase()
      console.log(suffix)
      if (suffix === 'doc' || suffix === 'docx') {
        return 'el-icon-doc'
      } else if (suffix === 'xls' || suffix === 'xlsx') {
        return 'el-icon-excel'
      } else if (suffix === 'pdf' || suffix === 'ofd') {
        return 'el-icon-pdf'
      } else if (suffix === 'zip' || suffix === '7z' || suffix === 'rar') {
        return 'el-icon-zip'
      } else if (suffix === 'mp4' || suffix === 'flv') {
        return 'el-icon-mp4'
      } else if (suffix === 'txt') {
        return 'el-icon-txt'
      } else if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpge') {
        return 'el-icon-img'
      } else if (suffix === 'ppt' || suffix === 'pptx') {
        return 'el-icon-ppt'
      } else {
        return 'el-icon-other'
      }
    },
    // 预览附件
    onlinePreviewOnlineEdit(type, id) {
      this.$refs.OnlinePreview.onlinePreviewFile(id, type)
    },
    // 文件下载
    downloadFile(id) {
      downLoadFileOpen('/file/fileBase/common/download?id=' + id)
    },
    /** 获取验证码 **/
    getCode() {
      this.repeatClick = true
      this.login.code = ''
      SMSVerificationCode(this.login.phone).then(response => {
        if (response.code === 200) {
          this.repeatClick = false
          this.btnShow = false
          var timeClock = setInterval(() => {
            this.num--
            if (this.num === 0) {
              this.btnShow = true
              clearInterval(timeClock)
              this.num = 60
            }
          }, 1000)
        } else {
          this.msgError(response.msg)
        }
      }).catch(() => {
        this.repeatClick = false
      })
    },
    /** 根据手机号, 用户名创建token **/
    viewLogin() {
      console.log('外部登陆')
      this.$refs['login'].validate(valid => {
        if (valid) {
          this.init('createToken')
        }
      })
    },
    setToken(token) {
      return Cookies.set('Admin-Token', token, { expires: new Date(new Date().getTime() + 60 * 1000 * 60) })
    },
    getToken() {
      const token = Cookies.get('Admin-Token')
      return token
    }
  }
}
</script>

<style scoped>
  .fileListPcClass {
    height: 90%;
    width: 90%;
    margin: auto;
    background: white;
    margin-top: 5%;
    padding: 30px;
  }
  .fileListMobileClass {
    margin: auto;
    background: white;
    padding: 15px;
  }
  /deep/ .el-collapse-item__header {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
